import cv2
import numpy as np
from typing import Tuple, Optional


class FrameUtils:
    @staticmethod
    def resize_frame(frame: np.ndarray, width: int, height: int) -> np.ndarray:
        """调整帧大小"""
        return cv2.resize(frame, (width, height))

    @staticmethod
    def add_timestamp(frame: np.ndarray, timestamp: str = None) -> np.ndarray:
        """在帧上添加时间戳水印"""
        if timestamp is None:                   # 如果时间戳为空，则获取当前时间
            from datetime import datetime
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")    # 格式化时间戳

        font = cv2.FONT_HERSHEY_SIMPLEX         # 字体
        cv2.putText(frame, timestamp, (10, 30), font, 0.7, (255, 255, 255), 2)  # 在帧上添加时间戳水印
        return frame

    @staticmethod
    def calculate_fps(frame_times: list, window_size: int = 30) -> float:
        """计算实时FPS（每秒帧数）"""
        if len(frame_times) < 2:                    # 如果帧数小于2，则返回0.0
            return 0.0

        # 使用滑动窗口计算FPS
        recent_times = frame_times[-window_size:]   # 获取最近30帧的时间
        if len(recent_times) < 2:                   # 如果帧数小于2，则返回0.0
            return 0.0

        time_diff = recent_times[-1] - recent_times[0]  # 计算时间差
        if time_diff > 0:                               # 如果时间差大于0，则计算FPS= (帧数-1) / 时间差
            return (len(recent_times) - 1) / time_diff  # 计算FPS
        return 0.0

    @staticmethod
    def add_fps_display(frame: np.ndarray, fps: float) -> np.ndarray:
        """在帧上显示FPS"""
        font = cv2.FONT_HERSHEY_SIMPLEX     # 字体
        fps_text = f"FPS: {fps:.1f}"        # 帧数
        cv2.putText(frame, fps_text, (10, 60), font, 0.7, (0, 255, 0), 2)  # 在帧上显示FPS
        return frame

    @staticmethod
    def add_info_display(frame: np.ndarray, fps: float, object_count: int) -> np.ndarray:
        """在帧上显示FPS和物体数量"""
        font = cv2.FONT_HERSHEY_SIMPLEX     # 字体
        font_scale = 0.7                    # 字体大小
        thickness = 2                       # 字体粗细

        # 显示FPS文本
        fps_text = f"FPS: {fps:.1f}"
        # 在帧的左上角（10, 30）位置绘制FPS文本，颜色为绿色
        cv2.putText(frame, fps_text, (10, 30), font, font_scale, (0, 255, 0), thickness)

        # 显示物体数量
        object_text = f"Objects: {object_count}"
        # 在帧的左上角（10, 60）位置绘制物体数量文本，颜色为绿色
        cv2.putText(frame, object_text, (10, 60), font, font_scale, (0, 255, 0), thickness)

        return frame  # 返回帧

    @staticmethod
    def check_frame_quality(frame: np.ndarray) -> bool:
        """检查帧质量"""
        if frame is None or frame.size == 0:            # 如果帧为空或帧大小为0，则返回False
            return False

        # 检查是否过暗或过亮
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        mean_brightness = np.mean(gray)                 # 计算灰度图的平均亮度

        if mean_brightness < 10 or mean_brightness > 245:  # 如果平均亮度小于10或大于245，则返回False
            return False

        return True
